package com.z.common.pro.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.z.common.pro.vo.TaskVo;
import com.z.common.web.base.BaseController;
import com.z.common.web.vo.request.PageVo;
import com.z.common.web.vo.response.Result;
import com.z.sys.entity.User;
import com.z.sys.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("process/control")
@Slf4j
public class ControlController extends BaseController {

    private final String prefix = "system/process/control/";

    @Autowired
    private IUserService userService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IdentityService identityService;

    /**
     * Describe: 获取流程监控列表视图
     * Param: modelAndView
     * Return: 流程监控列表视图
     */
    @GetMapping("main")
    @PreAuthorize("hasPermission('process/control/main','pro:control:main')")
    public ModelAndView main() {
        return jumpPage(prefix + "main");
    }

    /**
     * Describe: 获取流程监控列表数据
     * Param: modelAndView
     * Return: 流程监控列表数据
     */
    @GetMapping("data")
    @PreAuthorize("hasPermission('process/control/data','pro:control:data')")
    @ResponseBody
    public Result data(PageVo pageDomain, String name) {
        TaskQuery query = taskService.createTaskQuery();
        List<Task> list = query.orderByTaskCreateTime().desc().listPage(pageDomain.start(), pageDomain.end());

        List<TaskVo> data = new ArrayList<>();

        for(Task task : list){
            TaskVo taskVo = new TaskVo();
            if(StringUtils.isEmpty(task.getAssignee())){
                taskService.setAssignee(task.getId(), "1");

            }
            User user = userService.getOne(new QueryWrapper<User>().select("username").eq("id", task.getAssignee()));
            if(user!=null && StringUtils.isNotEmpty(user.getUsername())){
                taskVo.setStartedBy(user.getUsername());
            }
            taskVo.setId(task.getId());
            taskVo.setName(task.getName());
            if(StringUtils.isNotEmpty(task.getProcessDefinitionId())) {
                String[] strs = task.getProcessDefinitionId().split(":");
                taskVo.setDefinitionId(strs[2]);
                taskVo.setType(strs[0]);
                taskVo.setVersion(strs[1]);
            }
            taskVo.setInstanceId(task.getProcessInstanceId());
            data.add(taskVo);
        }
        int count = (int) query.orderByTaskCreateTime().desc().count();

        return Result.table(data, count);
    }
    /**
     * Describe: task删除接口
     * Param: id
     * Return: 文件流
     */
    @DeleteMapping("remove/{id}")
    @PreAuthorize("hasPermission('process/control/remove','pro:control:del')")
    @ResponseBody
    public Result remove(@PathVariable("id") String taskId){
        try{
            Task task = taskService.createTaskQuery().taskId(taskId).initializeFormKeys().singleResult();
            String id = task.getProcessInstanceId();
            runtimeService.deleteProcessInstance(id, "手动删除");
        } catch (Exception e){
            return Result.error(e.getMessage());
        }
        return Result.success();
    }

}
